package com.lfg.leetcode.leetcode0;

public class No28IndexOf {

    public static int strStr(String haystack, String needle) {
        if (null == needle || "".equals(needle)) {
            return 0;
        }
        if (null == haystack || "".equals(haystack)) {
            return -1;
        }
        int length = haystack.length();
        int length1 = needle.length();
        if (length < length1) {
            return -1;
        }
        int[] next = getNext(needle);

        int i = 0, j = 0;
        while (j < length && i < length1) {
            if (i == -1 || haystack.charAt(j) == needle.charAt(i)) {
                i++;
                j++;
            } else {
                i = next[i];
            }
            if (i >= length1) {
                return j - i;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        int l = strStr("bbbbbbbba", "a");
        System.out.println(l);
//        System.out.println("aaaaaaaaaxxxxxxxx".indexOf("xxx"));
    }


    public static int[] getNext(String content) {
        int length = content.length();
        int[] next = new int[length];
        next[0] = -1;
        int k = -1;
        for (int j = 0; j < length - 1; ) {
            if (k == -1 || content.charAt(k) == content.charAt(j)) {
                next[++j] = ++k;
            } else {
                k = next[k];
            }
        }
        return next;
    }

}

